<template>
	<view class="user-pages-choose-addr">

		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" leftIcon="icon-left" title="搜索地址" color="#000"
			backgroundColor="">
		</uni-nav-bar>
		<!-- #endif -->

		<fixed>
			<view class="fill-base">
				<!-- #ifndef H5 -->
				<image class="abs choose-bg" :src="`https://api.huixuananmm.com/admin/anmo/mine/choose-addr-bg.png`">
				</image>
				<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
				<!-- #endif -->
				<view class="fill-base pd-lg rel" style="border-radius: 40rpx 40rpx 0 0;">
					<search @input="toInput" @confirm="toSearch" type="input" :padding="0" :confirmSearch="true"
						:radius="30" :keyword="param.keyword" :isDel="true" height="70rpx"
						:placeholder="['coach','order','addr','useraddr','map'].includes(options.from) || (city_info&&!city_info.id)?`请搜索城市/区/县+地点`:`请搜索城市/区/县/地点`">
					</search>
				</view>
			</view>
		</fixed>
		<view class="space-lg" :style="{background:pageColor}"></view>
		<view @tap="toSelectAddr(index)" class="list-item flex-warp ml-lg mr-lg b-1px-b"
			v-for="(item,index) in list.data" :key="index">
			<i class="iconfont iconsousuodizhi"></i>
			<view class="flex-1 ml-md f-desc" style="color:#8A8A8A">
				<view class="f-paragraph c-title text-bold" style="min-height: 40rpx;padding-bottom: 6rpx;">
					<span :style="{color:aitem =='#'?primaryColor:''}" v-for="(aitem,aindex) in item.title_arr"
						:key="aindex">{{aitem =='#'?list.keyword:aitem}}</span>
				</view>
				<view class="flex-between">
					<view class="pr-lg"><span :style="{color:aitem =='#'?primaryColor:''}"
							v-for="(aitem,aindex) in item.address_arr"
							:key="aindex">{{aitem =='#'?list.keyword:aitem}}</span></view>
					<view>{{item._distance | handleFormatNum}}</view>
				</view>
			</view>
		</view>
		<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading">
		</load-more>

		<!-- #ifdef H5 -->
		<abnor :percent="`calc(100vh - 160rpx)`" :tip="[{ text: '暂无数据，请输入地址后搜索~', color: 0 }]"
			v-if="!loading&&list.data.length<=0&&list.current_page==1">
		</abnor>
		<!-- #endif -->
		<!-- #ifndef H5 -->
		<abnor :percent="`calc(100vh - 160rpx - ${configInfo.navBarHeight}px)`"
			:tip="[{ text: '暂无数据，请输入地址后搜索~', color: 0 }]" v-if="!loading&&list.data.length<=0&&list.current_page==1">
		</abnor>
		<!-- #endif -->
		<view class="space-footer" v-if="list.data.length>0"></view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				isLoad: false,
				options: {},
				param: {
					page: 1,
					keyword: ''
				},
				list: {
					data: [],
					current_page: 1,
					last_page: 1
				},
				loading: false
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			technicianParam: state => state.technician.param,
		}),
		async onLoad(options) {
			let {
				type = 0,
					from = 'user'
			} = options
			options.type = type * 1
			options.from = from
			this.options = options
			this.$util.setNavigationBarColor({
				bg: this.primaryColor,
				color: '#000000'
			})
			uni.setNavigationBarTitle({
				title: `搜索地址`
			})
			// #ifdef H5
			this.$jweixin.hideOptionMenu()
			// #endif
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.param.page = this.param.page + 1;
			this.loading = true;
			this.getList();
		},
		methods: {
			...mapMutations(['updateUserItem', 'updateServiceItem', 'updateTechnicianItem',
				'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
			]),
			toInput(val) {
				this.param.keyword = val
			},
			toSearch(val) {
				this.param.keyword = val
				if (!val) {
					this.$util.showToast({
						title: `请按提示输入地址后再搜索哦`
					})
					return
				}
				this.loading = true
				this.list.data = []
				this.param.page = 1
				this.getList()
			},
			async getList() {
				let {
					list: oldList,
				} = this
				let {
					from
				} = this.options
				let param = this.$util.deepCopy(this.param)
				let {
					lat,
					lng
				} = from == 'coach' ? this.userCoachStatus : this.location

				let {
					title = ''
				} = this.city_info
				if (from == 'coach') {
					title = ''
				}
				param.boundary = `region(${title},1,${lat},${lng})`
				let items = await this.$api.base.nearbyLocation(param)
				let {
					status,
					count = 0,
					data = []
				} = JSON.parse(items)
				let {
					keyword
				} = param
				if (data.length > 0) {
					data.map(item => {
						item.address = item.address || item.title
						item.title_arr = item.title.replace(keyword, `${keyword}#${keyword}`).split(keyword)
						item.address_arr = item.address.replace(keyword, `${keyword}#${keyword}`).split(
							keyword)
					})
				}
				let newList = {
					data,
					keyword,
					current_page: param.page,
					last_page: Math.ceil(count / 20)
				}
				if (status == 0) {
					if (this.param.page == 1) {
						this.list = newList
					} else {
						newList.data = oldList.data.concat(newList.data)
						this.list = newList
					}
				}
				this.loading = false
				this.$util.hideAll()
			},
			async toSelectAddr(index) {
				let {
					title,
					address,
					location,
					ad_info
				} = this.list.data[index]
				let param = Object.assign({}, this.technicianParam, {
					city_id: 0
				})
				this.updateTechnicianItem({
					key: 'param',
					val: param
				})
				let {
					type,
					from
				} = this.options
				let val = Object.assign({}, location, ad_info, {
					address: from == 'useraddr' ? address : title === address ? title : `${address} ${title}`
				})
				this.updateUserItem({
					key: 'location',
					val
				})
				if (['coach', 'order', 'addr', 'useraddr'].includes(from)) {
					let param = this.$util.pick(val, ['lat', 'lng', 'address', 'province', 'city', 'district'])
					if (from == 'useraddr') {
						param = Object.assign({}, param, {
							address_info: title
						})
					}
					if (!param.province && !param.city) {
						this.$util.showToast({
							title: `请选择具体的地址`
						})
						return
					}
					if (from == 'useraddr') {
						param.area = param.district || ''
					}
					if (['coach', 'order', 'addr'].includes(from)) {
						delete param.province
						delete param.city
					}
					delete param.district
					if (from == 'coach') {
						await this.$util.updateCoachAddr(param)
						this.$util.back()
					}
					if (from == 'order') {
						this.$util.getPage(-1).popupInfo.location = Object.assign({}, {
							map_type: 1,
							isIp: false,
						}, param)
					}
					if (['addr', 'useraddr'].includes(from)) {
						this.$util.getPage(-1).form = Object.assign({}, this.$util.getPage(-1).form, param)
					}
					this.$util.goUrl({
						url: 1,
						openType: `navigateBack`
					})
					return
				}
				if (from == 'map') {
					this.$util.getPage(-1).toConfirmUpdateLoca()
					this.$util.goUrl({
						url: 1,
						openType: `navigateBack`
					})
					return
				}

				let pages = getCurrentPages()
				let len = pages.length
				let prePage = ''
				if (len > 2) {
					prePage = pages[pages.length - 3].route
				}
				let updateArr = ['updateServiceItem',
					'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
				]
				updateArr.map(item => {
					this[item]({
						key: 'pageActive',
						val: false
					})
				})
				if (['pages/technician', 'user/pages/choose-technician'].includes(prePage)) {
					this.$util.getPage(-2).toChooseLocation(1)
					this.$util.goUrl({
						url: 2,
						openType: `navigateBack`
					})
				} else {
					this.updateUserItem({
						key: 'city_info',
						val: Object.assign({}, this.city_info, {
							id: 0
						})
					})
					this.updateUserItem({
						key: 'changeAddr',
						val: true
					})
					this.$util.goUrl({
						url: ['/pages/technician', '/user/pages/choose-technician'][type],
						openType: `reLaunch`
					})
				}
			}
		},
		filters: {
			handleFormatNum(val) {
				let text = ``
				if (val < 100) {
					text = val == 0 ? `` : `<100m`
				} else if (val > 999) {
					let num = (val / 1000).toFixed(2)
					text = `${num}km`
				} else if (val) {
					text = `${val}m`
				}
				return text
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #fff;
	}

	.user-pages-choose-addr {

		.choose-bg {
			width: 100%;
			height: 265rpx;
			top: 0;
			left: 0;
		}


		.list-item {
			padding: 37rpx 0;

			.iconsousuodizhi {
				font-size: 46rpx;
			}
		}
	}
</style>